#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.api import memcache
from google.appengine.ext.webapp.util import run_wsgi_app
import logging
import time
import datetime
import os
import oauth
import simplejson
import urllib
import urllib2
import random
import sys
from init import *
"""

"""
CONSUMER_KEY = '1ea44e71b7f4d0733804'
CONSUMER_SECRET_KEY = '24d2a53030ee5d2eead4e09c1e56be8e2a159e06'
class mixiGraphRefresh(webapp.RequestHandler):
    
    
    def get(self):
        url = 'https://secure.mixi-platform.com/2/token'
        token_params = {
                        'grant_type'    : 'refresh_token',
                        'client_id'     : CONSUMER_KEY,
                        'client_secret' : CONSUMER_SECRET_KEY,
                        'refresh_token' : self.request.get("refresh_token")
        }   
        token_res = urllib.urlopen(
             url,
             urllib.urlencode(token_params).encode("utf-8")
             ).read()
        token_dic = simplejson.loads(token_res)
        self.response.headers['Content-Type'] = 'aplication/json;charset=utf-8'
        #print token_res
        expires_date = datetime.datetime.utcnow() + datetime.timedelta(900)
        expires = expires_date.strftime("%d %b %Y %H:%M:%S GMT")
        for i in token_dic:
            self.response.headers.add_header('Set-Cookie', '%s=%s; expires=%s' % (i, token_dic[i], expires))
            
        #self.redirect('/')
        self.response.out.write(token_res)
        

application = webapp.WSGIApplication([('/refresh', mixiGraphRefresh)], debug=True)


def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
